package com.zqxq.lottery.api.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.zqxq.common.utils.DispatcherUtils;
import com.zqxq.lottery.api.config.WechatConfig;
import com.zqxq.lottery.api.config.YmlConfig;
import com.zqxq.lottery.api.service.IWechatService;
import com.zqxq.lottery.api.utils.HttpUtil;
import com.zqxq.lottery.api.utils.WechatUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;


@Service
@Slf4j
public class WechatServiceImpl implements IWechatService {


    @Autowired
    private YmlConfig ymlConfig;

    @Autowired
    private WechatConfig wechatConfig;

    @Override
    public JSONObject rechargeParams(HttpServletRequest request, Long userId, BigDecimal money) {
        return payParams(request, userId, ymlConfig.getPkId(),null,null, 0, money, "充值");
    }
    @Override
    public JSONObject consumeParams(HttpServletRequest request, Long userId, Long orderId, Long couponId, BigDecimal balance, BigDecimal money) {
        return payParams(request, userId, orderId,couponId,balance, 1, money, "消费");
    }

    private JSONObject payParams(HttpServletRequest request, Long userId, Long orderId,Long couponId,BigDecimal balance, Integer type, BigDecimal money, String payNotes){
        JSONObject returnJson = new JSONObject();
        try {
            Map<String,String> map = new HashMap<>();
            String nonceStr = UUID.randomUUID().toString().substring(0, 32);
            String outTradeNo = String.valueOf(orderId);
//            String totalFee = DispatcherUtils.parseString(money.multiply(new BigDecimal(100)).intValue());
            String totalFee = "1";
            String url = wechatConfig.getServerUrl();
            String appId = wechatConfig.getAppId();
            String mchId= wechatConfig.getMchId();
            String key = wechatConfig.getKey();
            String notifyUrl = wechatConfig.getNotifyUrl();
            String body = payNotes;
            long timestamp = System.currentTimeMillis() / 1000;
            map.put("appid", appId);
            map.put("mch_id", mchId);
            map.put("nonce_str",nonceStr);
            map.put("body", body);
            map.put("out_trade_no", outTradeNo);
            map.put("total_fee", totalFee);
            map.put("spbill_create_ip",request.getRemoteAddr());
            map.put("notify_url", notifyUrl);
            map.put("trade_type", "APP");
            map.put("attach", URLEncoder.encode( type + "," + userId + "," + couponId + "," + balance, "utf-8"));
            map.put("limit_pay", "no_credit");
            String paySign = WechatUtil.getPayCustomSign(map,key);
            map.put("sign",paySign);
            String xml= WechatUtil.ArrayToXml(map);
            String returnXmlStr = HttpUtil.doPostXml(url, xml);
            if (returnXmlStr.indexOf("SUCCESS") != -1) {
                Map<String, String> returnMap = WechatUtil.doXMLParse(returnXmlStr);
                System.out.println("returnMap:"+returnMap);
                String prepayId = returnMap.get("prepay_id");
                Map<String,String> signMap=new HashMap<>();
                signMap.put("appid", appId);
                signMap.put("partnerid", mchId);
                signMap.put("prepayid",prepayId);
                signMap.put("noncestr", nonceStr);
                signMap.put("timestamp", timestamp+"");
                signMap.put("package", "Sign=WXPay");
                String paySign2 = WechatUtil.getPayCustomSign(signMap,key);
                returnJson.put("appid",appId);
                returnJson.put("partnerid",mchId);
                returnJson.put("prepayid",prepayId);
                returnJson.put("package","Sign=WXPay");
                returnJson.put("noncestr",signMap.get("noncestr"));
                returnJson.put("timestamp",signMap.get("timestamp"));
                returnJson.put("sign",paySign2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("returnJson:"+returnJson.toString());
        return returnJson;
    }

    @Override
    public Map<String,String> getAccessToken(String code) {
        Map<String,String> result = new HashMap<>();
        try {
            String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                    + wechatConfig.getAppId() + "&secret=" + wechatConfig.getAppSecret() + "&code=" + code + "&grant_type=authorization_code";
            JSONObject jsonObject = HttpUtil.httpsRequest(URL, "GET", null);
            if (null != jsonObject) {
                System.out.println("jsonObject:" + jsonObject.toString());
                String openId = jsonObject.getString("openid");
                String unionId = jsonObject.getString("unionid");
                result.put("openId",openId);
                result.put("unionId",unionId);
            }

        } catch (Exception e) {
            log.error("wechat getAccessToken is error",e);
        }
        return result;
    }

}
